<?php

### Error handling

function PHPGWTErrorHandler($errno, $errstr, $errfile, $errline){
 die("Error #".$errno." in ".$errfile." at line ".$errline.": ".$errstr);
}

set_error_handler("PHPGWTErrorHandler");

function checkLastJsonError(){
	$error = json_last_error();
	
	switch($error){
		case JSON_ERROR_DEPTH:
			die('JSON Error: The maximum stack depth has been exceeded');
		case JSON_ERROR_STATE_MISMATCH:
			die('JSON Error: Invalid or malformed JSON');
		case JSON_ERROR_CTRL_CHAR:
			die('JSON Error: Control character error, possibly incorrectly encoded');
		case JSON_ERROR_SYNTAX:
			die('JSON Error: Syntax error');
		case JSON_ERROR_UTF8: 
			die('JSON Error: Malformed UTF-8 characters, possibly incorrectly encoded');
	}
}

### Processing request
$data = json_decode($_POST['data']);

checkLastJsonError();

if(!$data){
  die('Error parsing request:'.$_POST['data']);
}

$service = $data->service;
$function = $data->function;
$parameters = (array) $data->parameters;

$services = array();
$files = array();
$ret = NULL;

### Service definitions

$files['PrimitiveTestService'] = 'PrimitiveTestService.php';
$services['PrimitiveTestService'] = array();
$services["PrimitiveTestService"][] = "getBoolean2";
$services["PrimitiveTestService"][] = "getBoolean3";
$services["PrimitiveTestService"][] = "getChar2";
$services["PrimitiveTestService"][] = "sendByte";
$services["PrimitiveTestService"][] = "sendShort";
$services["PrimitiveTestService"][] = "sendInt";
$services["PrimitiveTestService"][] = "sendLong";
$services["PrimitiveTestService"][] = "sendFloat";
$services["PrimitiveTestService"][] = "sendDouble";
$services["PrimitiveTestService"][] = "sendBoolean";
$services["PrimitiveTestService"][] = "sendChar";
$services["PrimitiveTestService"][] = "getBoolean";
$services["PrimitiveTestService"][] = "getByte";
$services["PrimitiveTestService"][] = "getShort";
$services["PrimitiveTestService"][] = "getChar";
$services["PrimitiveTestService"][] = "getInt";
$services["PrimitiveTestService"][] = "getLong";
$services["PrimitiveTestService"][] = "getFloat";
$services["PrimitiveTestService"][] = "getDouble";

$files['StringTestService'] = 'StringTestService.php';
$services['StringTestService'] = array();
$services["StringTestService"][] = "sendString";
$services["StringTestService"][] = "sendUTF8String";
$services["StringTestService"][] = "getString";
$services["StringTestService"][] = "getUTF8String";

### Request validation and execution

if(in_array($function, $services[$service])){
  require $files[$service];
  $ret = call_user_func_array($function, $parameters);
}

$json = json_encode($ret);

checkLastJsonError();

print $json;

?>
